<template>
    <div>
        <el-container>
            <el-header>
                <el-menu
                    :default-active="activeIndex"
                    class="el-menu-demo"
                    mode="horizontal"
                    :ellipsis="false"
                    @select="handleSelect"
                >
                    <el-menu-item index="0">
                        <img
                            style="width: 150px"
                            src="../../assets/logo.png"
                            alt="logo"
                        />
                    </el-menu-item>
                    <el-menu-item index="1" @click="goToArticleDetail(null)">全部日记</el-menu-item>
                    <el-sub-menu index="2">
                        <template #title>日记分类</template>
                        <!-- 动态渲染日记分类选项 -->
                        <el-menu-item
                            v-for="category in articleCategories"
                            :key="category.id"
                            :index="`2-${category.id}`"
                            @click="goToArticleDetail(category.id)"
                        >
                            {{ category.categoryName }}
                        </el-menu-item>
                    </el-sub-menu>
                    <el-menu-item index="3" @click="goToScheduleDetail(null)">全部日程</el-menu-item>
                    <el-sub-menu index="4">
                        <template #title>日程分类</template>
                        <!-- 动态渲染日程分类选项 -->
                        <el-menu-item
                            v-for="category in scheduleCategories"
                            :key="category.id"
                            :index="`4-${category.id}`"
                            @click="goToScheduleDetail(category.id)"
                        >
                            {{ category.categoryName }}
                        </el-menu-item>
                    </el-sub-menu>
                    <el-menu-item index="5" @click="goToScheduleCalendar()">日历</el-menu-item>
                    <div style="display: flex; justify-content: flex-end; width: 100%;align-items: center;">
                        <div>智慧用户：<strong>{{ userInfoStore.info.nickname }}</strong></div>
                        <!-- 下拉菜单 -->
                        <!-- command: 条目被点击后会触发，在事件函数上可以声明一个参数，接收条目对应的指令 -->
                        <el-dropdown placement="bottom-end" @command="handleCommand">
                        <span class="el-dropdown__box">
                            <el-avatar :src="userInfoStore.info.userPic?userInfoStore.info.userPic:avatar"/>
                            <el-icon>
                                <CaretBottom/>
                            </el-icon>
                        </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
                                    <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
                                    <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码
                                    </el-dropdown-item>
                                    <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </el-menu>
            </el-header>
            <el-main>
                <router-view></router-view>
            </el-main>
            <el-row></el-row>
            <el-footer style="text-align: center; color: gray; font-size: 12px;">
                CleverestDiary ©2025 Created by Cleverest. All Rights Reserved.
            </el-footer>
        </el-container>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import avatar from "@/assets/default.png";
import {CaretBottom, Crop, EditPen, SwitchButton, User} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {useTokenStore} from "@/stores/token.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {userInfoService} from "@/api/user.js";

//日记分类
//声明一个异步的函数
import {articleCategoryListService} from "@/api/article.js";

// 声明 articleCategories 变量
const articleCategories = ref([
    {
        "id": 3,
        "categoryName": "美食",
        "categoryAlias": "my",
        "createTime": "2023-09-02 12:06:59",
        "updateTime": "2023-09-02 12:06:59"
    }
])

const articleCategoryList = async () => {
    try
    {
        let result = await articleCategoryListService();
        articleCategories.value = result.data;
    }catch (error){
        console.log("获取日记列表失败："+error);
    }
}

//日程分类
//声明一个异步的函数
import {scheduleCategoryListService} from "@/api/schedule.js";

// 声明 scheduleCategories 变量
const scheduleCategories = ref([
    {
        "id": 3,
        "categoryName": "美食",
        "categoryAlias": "my",
        "createTime": "2023-09-02 12:06:59",
        "updateTime": "2023-09-02 12:06:59"
    }
])

const scheduleCategoryList = async () => {
    try
    {
        let result = await scheduleCategoryListService();
        scheduleCategories.value = result.data;
    }catch (error){
        console.log("获取日程列表失败："+error);
    }
}

const router = useRouter();
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

// 调用函数，获取用户详细信息
const getUserInfo = async () => {
    // 调用接口
    let result = await userInfoService();
    // 数据存储到 pinia 中
    userInfoStore.setInfo(result.data);
}

onMounted(async () => {
    await getUserInfo();
    await articleCategoryList();
    await scheduleCategoryList();
});

// 条目被点击后调用的函数
const handleCommand = (command) => {
    // 判断指令
    if (command === 'logout') {
        // 退出登录
        ElMessageBox.confirm(
            '你确认要退出吗？',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                // 退出登录
                // 1. 清空 pinia 中存储的 token 以及个人信息
                tokenStore.removeToken()
                userInfoStore.removeInfo()

                // 2. 跳转到登录页面
                router.push('/login')
                ElMessage({
                    type: 'success',
                    message: '退出登录成功',
                })

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '用户取消了退出登录',
                })
            })
    } else {
        // 路由
        router.push('/user/' + command)
    }
}

const activeIndex = ref('1')

// 新增跳转到文章详情页的函数
const goToArticleDetail = (categoryId) => {
    router.push({
        path: '/article/detail',
        query: { categoryId }
    });
}

// 新增跳转到日程详情页的函数
const goToScheduleDetail = (categoryId) => {
    router.push({
        path: '/schedule/detail',
        query: { categoryId }
    });
}

// 新增跳转到日历的函数
const goToScheduleCalendar = () => {
    router.push({
        path: '/schedule/calendar'
    });
}

// 原有的 handleSelect 函数可以根据需要保留或调整
const handleSelect = (key) => {
    if (key === '0') {
        router.push('/');
    } else if (key === '1') {
        // 调用新增的跳转日记列表函数
        goToArticleDetail(null);
    } else if (key.startsWith('2-')) {
        const categoryId = key.split('-')[1];
        // 调用新增的跳转日记列表函数
        goToArticleDetail(categoryId);
    } else if (key === '3') {
        // 调用新增的跳转日记列表函数
        goToScheduleDetail(null);
    } else if (key.startsWith('4-')) {
        const categoryId = key.split('-')[1];
        // 调用新增的跳转日记列表函数
        goToScheduleDetail(categoryId);
    }else if(key==='5'){
        // 调用新增跳转到日历的函数
        goToScheduleCalendar();
    }
};
articleCategoryList();
scheduleCategoryList();
</script>

<style scoped>
.carousel-image {
    width: 100%;
    height: 600px;
    object-fit: cover;
    transition: filter 0.3s ease; /* 添加过渡效果，使模糊变化更平滑 */
}

.el-dropdown__box {
    display: flex;
    align-items: center;

    .el-icon {
        color: #999;
        margin-left: 10px;
    }

    &:active,
    &:focus {
        outline: none;
    }
}

/* 调整菜单项的间距 */
.el-menu--horizontal > .el-menu-item:nth-child(1) {
    margin-right: 20px; /* 增加菜单项之间的间距 */
}

/* 调整下拉菜单触发按钮的样式 */
.el-dropdown__box {
    cursor: pointer; /* 鼠标悬停时显示手型 */
    transition: color 0.3s ease; /* 颜色过渡效果 */
}

.el-dropdown__box:hover {
    color: #409EFF; /* 鼠标悬停时的颜色 */
}
</style>